import { useEffect, useRef, useState } from 'react'
import styles from './index.module.less'
import cm from 'classnames'

const Index = (props) => {
  const { children } = props
  const [isHover, setHover] = useState(false)
  const [canSwitch, setSwitch] = useState(false)
  const [scroll, setScroll] = useState(0)
  const ref = useRef(null)
  useEffect(() => {
    const click = () => {
      const width = ref.current.clientWidth
      const offWidth = ref.current.scrollWidth
      setSwitch(offWidth > width)
    }
    click()
    const leftShow = () => {
      setScroll(ref.current.scrollLeft)
    }
    ref.current.addEventListener('scroll', leftShow)
    window.addEventListener('resize', click)
    return () => {
      window.removeEventListener('resize', click)
      ref.current?.removeEventListener('scroll', leftShow)
    }
  }, [])

  const toLeft = () => {
    ref.current.scrollTo(0, 0)
    setScroll(0)
  }
  const toRight = () => {
    ref.current.scrollTo(ref.current.scrollWidth, 0)
    setScroll(ref.current.scrollWidth)
  }
  return (
    <div className={styles.content} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      {canSwitch && isHover && !!scroll && (
        <div onClick={toLeft} className={cm(styles.switch, styles.switchLeft)}>
          <img src="/images/switch.webp" alt="" />
        </div>
      )}
      <div className={styles.box} ref={ref}>
        {children}
      </div>

      {canSwitch && isHover && (
        <div onClick={toRight} className={cm(styles.switch, styles.switchRight)}>
          <img src="/images/switch.webp" alt="" />
        </div>
      )}
    </div>
  )
}

export default Index
